<?php


namespace App\Aspect;

use App\Annotation\LogAnnotation;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Server\Response;

class LogerAspect extends AbstractAspect
{

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    // 要切入的注解，具体切入的还是使用了这些注解的类，仅可切入类注解和类方法注解
    public $annotations = [
        LogAnnotation::class
    ];


    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {

        $result = $proceedingJoinPoint->process();
        try {
            $adminId = $this->request->getHeaderLine('admin_id');

            $annotation = $proceedingJoinPoint->getAnnotationMetadata();
            foreach ($annotation->method as $key => $value) {
                $modul = $value->modul;
                $action = $value->action;
            };

            if (strpos($result->getHeaderLine("content-type"), 'application/json') !== false) {
                $content = $result->getBody()->getContents();
            }
            Db::table('admin_log')->insert([
                'modul' => $modul ?? "未知",
                'action' => $action ?? "未知",
                'headers' => json_encode($this->request->getHeaders()),
                'request' => json_encode($this->request->all()),
                'respone' => $content ?? "",
                'create_time' => time(),
                'update_time' => time(),
                'admin_id' => intval($adminId),
                'class' => $proceedingJoinPoint->getReflectMethod()->class,
                'method' => $proceedingJoinPoint->getReflectMethod()->name,
            ]);
        } catch (\Throwable $e) {
            var_dump($e->getMessage());
        }
        // 在调用后进行某些处理
        return $result;
    }
}